package com.rj.framework.context;

import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 类型安全的上下文实现
 */
public class GenericContext<G extends GlobalContext> implements Context<G> {
    private final G globalContext;
    private final Map<Class<?>, Object> inputMap = new ConcurrentHashMap<>();
    private final Map<Class<?>, Object> outputMap = new ConcurrentHashMap<>();
    private final Map<String, Object> parameters = new ConcurrentHashMap<>();

    public GenericContext(G globalContext) {
        this.globalContext = globalContext;
    }

    @Override
    public <T> T getInput(Class<T> type) {
        return type.cast(inputMap.get(type));
    }

    public void setInput(Object value) {
        inputMap.put(value.getClass(), value);
    }

    @Override
    public <T> void setOutput(Class<? super T> type, T value) {
        outputMap.put(type, value);
    }

    @Override
    public <T> T getParameter(String key, Class<T> type) {
        Object value = parameters.get(key);
        return value != null ? type.cast(value) : null;
    }

    @Override
    public void setParameter(String key, Object value) {
        parameters.put(key, value);
    }

    @Override
    public G getGlobalContext() {
        return globalContext;
    }

    @Override
    public Map<String, Object> getParameters() {
        return Collections.unmodifiableMap(parameters);
    }
}
